"""
球队模型
"""
from sqlalchemy import Column, String, Float, Integer, DateTime, Text
from sqlalchemy.sql import func
from app.core.database import Base


class Team(Base):
    """球队表"""
    __tablename__ = "teams"
    
    id = Column(String(36), primary_key=True, index=True)
    name = Column(String(200), nullable=False, index=True)
    logo = Column(String(500))
    description = Column(Text)
    
    # 队长信息
    captain_id = Column(String(36), nullable=False, index=True)
    captain_name = Column(String(100))
    
    # 成员统计
    member_count = Column(Integer, default=1)
    max_members = Column(Integer, default=30)
    
    # 其他信息
    city_id = Column(String(36), index=True)
    city_name = Column(String(100))  # 城市名称
    founded_date = Column(String(20))  # 建队日期 (YYYY-MM-DD格式)
    match_count = Column(Integer, default=0)  # 本月比赛场次
    win_rate = Column(Float, default=0.0)  # 胜率
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "name": self.name,
            "logo": self.logo,
            "description": self.description,
            "captainId": self.captain_id,
            "captainName": self.captain_name,
            "memberCount": self.member_count,
            "maxMembers": self.max_members,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "cityId": self.city_id,
            "cityName": self.city_name,
            "foundedDate": self.founded_date,
            "matchCount": self.match_count,
            "winRate": self.win_rate
        }


class TeamMember(Base):
    """球队成员表"""
    __tablename__ = "team_members"
    
    id = Column(String(36), primary_key=True, index=True)
    team_id = Column(String(36), nullable=False, index=True)
    user_id = Column(String(36), nullable=False, index=True)
    user_name = Column(String(100), nullable=False)
    avatar = Column(String(500))
    
    # 位置和角色
    positions = Column(String(200))  # JSON数组字符串
    role = Column(String(20), default="member")  # captain, member
    
    # 统计
    join_date = Column(DateTime(timezone=True), server_default=func.now())
    match_count = Column(Integer, default=0)  # 参赛次数
    rating = Column(Float, default=0.0)  # 队内评分
    
    def to_dict(self):
        """转换为字典"""
        import json
        return {
            "userId": self.user_id,
            "userName": self.user_name,
            "avatar": self.avatar,
            "positions": json.loads(self.positions) if self.positions else [],
            "role": self.role,
            "joinDate": self.join_date.isoformat() if self.join_date else None,
            "matchCount": self.match_count,
            "rating": self.rating
        }

